<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\notify\gateway;

use app\common\manager\PlatformManager;
use app\common\manager\ProxyManager;
use app\common\manager\UserAccountManager;
use app\common\model\Config;
use app\common\model\Order;
use app\common\model\PayLog;
use app\common\model\Platform\Log;
use app\common\model\Proxy;
use app\common\model\RechargeOrder;
use app\common\model\Reward;
use app\common\model\User;
use app\common\model\UserCoupon;
use think\Db;
use think\Exception;

class Recharge
{
    public function dealWith($response,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            //file_put_contents('recharge.txt','step:1',FILE_APPEND);
            if (!$orderInfo = Order::where('order',$response['out_trade_no'])->find()){
                throw new Exception('当前记录不存在');
            }
            //file_put_contents('recharge.txt','step:2',FILE_APPEND);
            if ($orderInfo['pay_state'] != Order::PAY_STATE_INIT){
                throw new Exception('当前订单已处理');
            }
            //file_put_contents('recharge.txt','step:3',FILE_APPEND);
            if ($response['result_code'] == 'SUCCESS') {
                //file_put_contents('recharge.txt','step:4',FILE_APPEND);
                if(!Order::update([
                    'trilateral_pay_order'=>$response['transaction_id'],
                    'pay_date'=>strtotime($response['time_end']),
                    'up_date'=>time(),
                    'pay_state'=>Order::PAY_STATE_SUCCESS
                ],['po_id'=>$orderInfo['po_id']])){
                    throw new Exception('订单更新失败');
                }
                //file_put_contents('recharge.txt','step:5',FILE_APPEND);
                if(!RechargeOrder::update([
                    'payamount'=>bcdiv($response['cash_fee'],100,2),
                    'paytime'=>strtotime($response['time_end']),
                    'updatetime'=>time(),
                    'status'=>RechargeOrder::STATUS_TYPE_SUCCESS
                ],['orderid'=>$response['out_trade_no']])){
                    throw new Exception('订单更新失败');
                }
                //file_put_contents('recharge.txt','step:6',FILE_APPEND);
                //file_put_contents('recharge.txt','step:611'.json_encode($orderInfo),FILE_APPEND);
                $result = UserAccountManager::money($orderInfo['user_id'],$orderInfo['order_money'],UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_RECHARGE,['relation_id'=>$orderInfo['po_id'],'relation_order'=>$orderInfo['order']],false);
                //file_put_contents('recharge.txt','step:61',FILE_APPEND);
                if ($result['code']!=UserAccountManager::$successCode){
                    throw new Exception('账户更新失败');
                }

                if ($orderInfo['user_coupon_id'] && $orderInfo['pref_money'] > 0){

                    if (!UserCoupon::where('id', $orderInfo['user_coupon_id'])->update(['block' => UserCoupon::BLOCK_NO,'status'=>UserCoupon::STATUS_USED,'update_time'=>time()])){
                        throw new Exception('优惠券使用失败，请稍后再试');
                    }
                }
                //file_put_contents('recharge.txt','step:61',FILE_APPEND);
                /**
                 * 根据用户的上级找出是否为代理，如果为代理则奖励代理，并且记录平台出账金额
                 */
                $cityCode = User::where('id',$orderInfo['user_id'])->value('city');
                //file_put_contents('recharge.txt','step:62',FILE_APPEND);
                if ($cityCode && $recharge_reward_rate = Config::where('name','recharge_reward_rate')->value('value')){

                    $proxyInfo = Proxy::where('city',$cityCode)->find();
                    if($proxyInfo && !$orderInfo['user_coupon_id']){
                            $money = bcdiv(bcmul($orderInfo['order_money'],$recharge_reward_rate,4),100,2);
                            $resultProxyUser = UserAccountManager::money($proxyInfo['user_id'],$money,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_PROXY_RECHARGE_REWARD,['relation_id'=>$orderInfo['po_id'],'relation_order'=>$orderInfo['order']],false);
                            if ($resultProxyUser['code']!=UserAccountManager::$successCode){
                                throw new Exception($resultProxyUser['message']);
                            }

                            $resultPlatform = PlatformManager::platformLog($money,date('Y-m-d H:i:s',time()),Log::DIRECTIVE_OUT,Log::TYPE_RECHARGE_PROXY_REWARD,['recipient'=>$proxyInfo['user_id'],'relation_id'=>$orderInfo['po_id'],'relation_order'=>$orderInfo['order']],false);
                            if ($resultPlatform['code']!=PlatformManager::$successCode){
                                throw new Exception($resultPlatform['message']);
                            }

                            $resultProxy = ProxyManager::Statistics($money,date('Y-m-d H:i:s',time()),$proxyInfo['user_id'],$proxyInfo['id'],false);
                            if ($resultProxy['code']!=ProxyManager::$successCode){
                                throw new Exception($resultProxy['message']);
                            }

                    }
                }
                //file_put_contents('recharge.txt','step:9',FILE_APPEND);
                if ($rewardInfo = Reward::where('begin','<',$orderInfo['order_money'])->where('id','=',Db::table('fa_recharge_reward')->where('begin','<',$orderInfo['order_money'])->max('id'))->find()){
                    //file_put_contents('recharge.txt','step:10',FILE_APPEND);
                    $rewardMoney = bcdiv(bcmul($orderInfo['order_money'],$rewardInfo['rate'],4),100,2);
                    $result = UserAccountManager::money($orderInfo['user_id'],$rewardMoney,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_RECHARGE_REWARD,['relation_id'=>$orderInfo['po_id'],'relation_order'=>$orderInfo['order']],false);
                    if ($result['code']!=UserAccountManager::$successCode){
                        throw new Exception('账户更新失败');
                    }
                    //file_put_contents('recharge.txt','step:11',FILE_APPEND);
                    $resultPlatform = PlatformManager::platformLog($rewardMoney,date('Y-m-d H:i:s',time()),Log::DIRECTIVE_OUT,Log::TYPE_RECHARGE,['recipient'=>$orderInfo['user_id'],'relation_id'=>$orderInfo['po_id'],'relation_order'=>$orderInfo['order']],false);
                    if ($resultPlatform['code']!=PlatformManager::$successCode){
                        throw new Exception($resultPlatform['message']);
                    }
                    //file_put_contents('recharge.txt','step:12',FILE_APPEND);
                }
                //file_put_contents('recharge.txt','step:13',FILE_APPEND);
                if(!PayLog::update(['processed'=>PayLog::PROCESSED_STATUS_YES,'update_time'=>time()],['order'=>$response['out_trade_no']])){
                    throw new Exception('订单日志更新失败');
                }

                //file_put_contents('recharge.txt','step:14',FILE_APPEND);

            }

            if ($isTrans)
                Db::commit();
            return ['code'=>1,'message'=>'success'];
        }catch (Exception $exception){
            file_put_contents('recharge.txt','exception:'.$exception->getMessage(),FILE_APPEND);
            if ($isTrans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage()];
        }
    }
}